<?php 
if (!$GET_service || $GET_service != "novoSetor") {
	die("<script>window.location='../?'</script>");
}

if (!isset($_SESSION['loggeduser']) || $_SESSION['loggeduser']['id'] == "") {
	die("<script>window.location='./?'</script>");
}
header('Content-Type: text/json; charset=UTF-8');

$groupname = $_POST['groupname'];
$userfriends = $_POST['friends'];
$accepted_group = 'pending';

$division = explode(",",$userfriends);

$db->begin();
$result1 = $db->insert_sql("INSERT INTO `groups` (`gro_name`,`gro_user`)VALUES ('".$groupname."', '".$_SESSION['loggeduser']['id']."');");
$id = $result1;
  
$values = "";
$i = 0;
$status = 'pending';
while ($i < sizeof($division)) {
	if($division[$i] != 0){
		$values .= ", ('".$division[$i]."', '".$id."','".$status."') ";
	}
	$i++;
}
$values = substr($values, 0, -2);
if ($i == 0) { $values = ""; }

//if($idgroup == ''){
$result2 = $db->insert_sql("INSERT INTO `groupsmembers` (`mem_friend` , `mem_group`,`mem_status`) VALUES (".$_SESSION['loggeduser']['id'].", ".$id.", 'Accepted') ".$values.";");
//}else if($idgroup != '' && $friendstatus == 'accepted'){
//	$result3 = $db->update_sql("UPDATE `groupsmembers` SET mem_status='accepted' WHERE mem_group='".$idgroup."' AND mem_friend='".$_SESSION['loggeduser']['id']."'");
//}
//else if($idgroup != '' && $friendstatus == 'recused'){
//	$result3 = $db->update_sql("UPDATE `groupsmembers` SET mem_status='recused' WHERE mem_group='".$idgroup."' AND mem_friend='".$_SESSION['loggeduser']['id']."'");
// }
if ($result1 && $result2) {
		$db->commit();
		die(json_encode(Array("status" => "OK")));
	} else {
		$db->rollback();
		die(json_encode(Array("status" => "ERROR")));
	}	
?>